<template>
  <div class="roles-container">
    <div class="roles-header">
      <h1>角色管理</h1>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="角色分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable @change="handleSearch">
            <el-option
              v-for="cat in roleStore.categories"
              :key="cat.categoryCode"
              :label="cat.categoryName"
              :value="cat.categoryCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" :value="null" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="审核中" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 角色列表 -->
    <el-card class="roles-list">
      <el-table
        v-loading="roleStore.loading"
        :data="roleStore.roleList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="roleId" label="ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" width="150" />
        <el-table-column prop="category" label="角色类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.categoryCode)">
              {{ getCategoryName(row.categoryCode) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="角色来源" width="120" />
        <el-table-column prop="personality" label="性格特点" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="viewRole(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button size="small" type="primary" @click="editRole(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button size="small" type="success" @click="chatWithRole(row)">
                <el-icon><ChatDotRound /></el-icon>
                聊天
              </el-button>
              <el-button size="small" type="danger" @click="deleteRole(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="roleStore.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色分类" prop="category">
          <el-select v-model="roleForm.category" placeholder="请选择角色分类">
            <el-option
              v-for="cat in roleStore.categories"
              :key="cat.categoryCode"
              :label="cat.categoryName"
              :value="cat.categoryCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色来源" prop="source">
          <el-input v-model="roleForm.source" placeholder="请输入角色来源" />
        </el-form-item>
        <el-form-item label="性格特点" prop="personality">
          <el-input
            v-model="roleForm.personality"
            type="textarea"
            :rows="3"
            placeholder="请输入性格特点"
          />
        </el-form-item>
        <el-form-item label="语言风格" prop="languageStyle">
          <el-input
            v-model="roleForm.languageStyle"
            type="textarea"
            :rows="3"
            placeholder="请输入语言风格"
          />
        </el-form-item>
        <el-form-item label="背景知识" prop="backgroundKnowledge">
          <el-input
            v-model="roleForm.backgroundKnowledge"
            type="textarea"
            :rows="4"
            placeholder="请输入背景知识"
          />
        </el-form-item>
        <el-form-item label="角色图片" prop="image">
          <el-input v-model="roleForm.image" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="TTS配置" prop="ttsConfig">
          <el-input v-model="roleForm.ttsConfig" placeholder="请输入TTS配置" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="roleForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="审核中" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitForm">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 角色详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="角色详情"
      width="600px"
    >
      <div v-if="currentRole" class="role-detail">
        <div class="role-image">
          <img v-if="currentRole.image" :src="currentRole.image" alt="角色图片" />
          <div v-else class="no-image">暂无图片</div>
        </div>
        <div class="role-info">
          <h3>{{ currentRole.roleName }}</h3>
          <p><strong>类型：</strong>{{ getCategoryName(currentRole.categoryCode) }}</p>
          <p><strong>来源：</strong>{{ currentRole.source }}</p>
          <p><strong>性格：</strong>{{ currentRole.personality }}</p>
          <p><strong>语言风格：</strong>{{ currentRole.languageStyle }}</p>
          <p><strong>背景知识：</strong>{{ currentRole.backgroundKnowledge }}</p>
          <p><strong>状态：</strong>{{ getStatusName(currentRole.status) }}</p>
          <p><strong>创建时间：</strong>{{ currentRole.createTime }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useRoleStore } from '@/stores/role'
import { ElMessageBox, ElMessage } from 'element-plus'

const router = useRouter()
const roleStore = useRoleStore()

// 搜索表单
const searchForm = reactive({
  category: null,
  status: null
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10
})

// 对话框状态
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)

// 当前角色
const currentRole = ref(null)

// 角色表单
const roleFormRef = ref()
const roleForm = reactive({
  roleId: null,
  roleName: '',
  category: '',
  source: '',
  personality: '',
  languageStyle: '',
  backgroundKnowledge: '',
  image: '',
  ttsConfig: '',
  status: 1
})

// 表单验证规则
const roleRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择角色类型', trigger: 'change' }
  ],
  source: [
    { required: true, message: '请输入角色来源', trigger: 'blur' }
  ],
  personality: [
    { required: true, message: '请输入性格特点', trigger: 'blur' }
  ],
  languageStyle: [
    { required: true, message: '请输入语言风格', trigger: 'blur' }
  ],
  backgroundKnowledge: [
    { required: true, message: '请输入背景知识', trigger: 'blur' }
  ]
}

// 获取角色列表
const fetchRoles = async () => {
  const params = {
    page: pagination.page,
    pageSize: pagination.pageSize,
    ...searchForm
  }
  await roleStore.fetchRoleList(params)
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchRoles()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    category: '',
    status: null
  })
  pagination.page = 1
  fetchRoles()
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchRoles()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchRoles()
}

// 显示新增对话框
const showCreateDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑角色
const editRole = (row) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(roleForm, {
    roleId: row.roleId,
    roleName: row.roleName,
    category: row.categoryCode,
    source: row.source,
    personality: row.personality,
    languageStyle: row.languageStyle,
    backgroundKnowledge: row.backgroundKnowledge,
    image: row.image,
    ttsConfig: row.ttsConfig,
    status: row.status
  })
}

// 查看角色
const viewRole = (row) => {
  currentRole.value = row
  viewDialogVisible.value = true
}

// 与角色聊天
const chatWithRole = (row) => {
  router.push(`/chat/${row.roleId}`)
}

// 删除角色
const deleteRole = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await roleStore.removeRole(row.roleId)
    fetchRoles()
  } catch {
    // 用户取消
  }
}

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await roleStore.updateRoleInfo(roleForm)
    } else {
      await roleStore.createNewRole(roleForm)
    }
    
    dialogVisible.value = false
    fetchRoles()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(roleForm, {
    roleId: null,
    roleName: '',
    category: null,
    source: '',
    personality: '',
    languageStyle: '',
    backgroundKnowledge: '',
    image: '',
    ttsConfig: '',
    status: 1
  })
  roleFormRef.value?.clearValidate()
}

// 获取角色类型名称
const getCategoryName = (code) => {
  const item = roleStore.categories.find(c => c.categoryCode === code)
  return item ? item.categoryName : '未知'
}

// 获取角色类型样式
const getCategoryType = () => {
  return 'info'
}

// 获取状态名称
const getStatusName = (status) => {
  const map = { 0: '禁用', 1: '启用', 2: '审核中' }
  return map[status] || '未知'
}

// 获取状态样式
const getStatusType = (status) => {
  const map = { 0: 'danger', 1: 'success', 2: 'warning' }
  return map[status] || ''
}

onMounted(async () => {
  await roleStore.fetchCategories()
  fetchRoles()
})
</script>

<style scoped>
.roles-container {
  padding: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

.roles-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.roles-header h1 {
  color: #333;
  font-size: 28px;
  font-weight: 600;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.roles-list {
  border-radius: 12px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.role-detail {
  display: flex;
  gap: 20px;
}

.role-image {
  flex-shrink: 0;
  width: 150px;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  color: #999;
  font-size: 14px;
}

.role-info {
  flex: 1;
}

.role-info h3 {
  color: #333;
  margin: 0 0 15px 0;
  font-size: 20px;
  font-weight: 600;
}

.role-info p {
  margin: 8px 0;
  color: #666;
  line-height: 1.6;
}

:deep(.el-card) {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-table) {
  border-radius: 8px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  font-size: 12px;
  min-width: auto;
  white-space: nowrap;
}

.action-buttons .el-button .el-icon {
  font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 1400px) {
  .action-buttons .el-button {
    padding: 4px 6px;
    font-size: 11px;
  }
  
  .action-buttons .el-button .el-icon {
    font-size: 11px;
  }
}
</style>
